#!/bin/bash
git clone https://github.com/prometheus-operator/prometheus-operator.git
# 为Promethues Operator创建一个单独的命名空间monitoring
kubectl create namespace monitoring
# 安装Prometheus Operator的Deployment实例
cd prometheus-operator/
# 替换一下bundle.yaml文件中所有namespace定义，由default修改为monitoring
grep -l 'namespace: monitoring' bundle.yaml | xargs sed -i 's/namespace: default/namespace: monitoring/g'
kubectl -n monitoring apply -f bundle.yaml
# 查看Prometheus Operator部署状态，以确保已正常运行
kubectl -n monitoring get pods
# 在Monitoring命名空间下创建一个Prometheus实例
cat <<EOF > prometheus-inst.yaml
apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:
  name: inst
  namespace: monitoring
spec:
  resources:
    requests:
      memory: 400Mi
EOF

kubectl create -f prometheus-inst.yaml
# 查看monitoring命名空间下的statefulsets资源
kubectl -n monitoring get statefulsets
# 查看Pod实例
kubectl -n monitoring get pods
# 通过port-forward访问Prometheus实例
# kubectl -n monitoring port-forward --address 0.0.0.0 statefulsets/prometheus-inst 9090:9090
# 使用ServiceMonitor管理监控配置
cat <<EOF > example-app-service-monitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: example-app
  namespace: monitoring
  labels:
    team: frontend
spec:
  namespaceSelector:
    matchNames:
    - default
  selector:
    matchLabels:
      app: example-app
  endpoints:
  - port: web
EOF

kubectl create -f example-app-service-monitor.yaml